package com.booksystem.campuslibrarymanagementsystem.controller.user;

import com.booksystem.campuslibrarymanagementsystem.commen.request.adminrequest.AnnouncementManagement.Announcementlist;
import com.booksystem.campuslibrarymanagementsystem.commen.result.Result;
import com.booksystem.campuslibrarymanagementsystem.entity.AccountTable;
import com.booksystem.campuslibrarymanagementsystem.entity.SystemTable;
import com.booksystem.campuslibrarymanagementsystem.service.AccountTableService;
import com.booksystem.campuslibrarymanagementsystem.service.SystemTableService;
import com.booksystem.campuslibrarymanagementsystem.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/User")
@Api(tags = "系统公告")
public class AnnouncementController {

    SystemTable systemTable = new SystemTable();
    @Autowired
    private AccountTableService accountTableService;
    @Autowired
    private SystemTableService systemTableService;



    /**
     * 2.公告列表。
     *
     * @return Result.success();or return Result.fail();
     * @RequestBody Announcementlist（token）
     * 1.解析获得的token值，并保存到键值对Map-parsed中
     * 2.判断parsed是否为null
     * 3.null：返回失败信息-请输入正确token值。不为null：判断解析到的身份码是否为admin。
     * 4.不为admin；返回失败信息-身份权限不足。是admin：判断解析到的学号是否在account表中存在。
     * 5.不存在：返回失败信息-该学号不存在。存在：获取systemTable的所有数据并保存到list-systemTable中，之后判断systemTable是否为空
     * 6.为空：返回失败信息-没有公告数据，不为空：返回systemTable数据至前端
     */
    @PostMapping("/announcement")
    @ApiOperation(value = "公告列表", notes = "获取公告列表信息")
    public Result announcementList(@RequestBody Announcementlist announcementlist) {
        Map<String, Object> parsed = JwtUtil.tokenPre(announcementlist.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                AccountTable accountTable = accountTableService.queryByAccount((String) account);
                if (accountTable != null) {
                    // 查询最新的公告记录
                    SystemTable latestAnnouncement = systemTableService.findLatestAnnouncement();
                    if (latestAnnouncement != null) {

                        return Result.success(latestAnnouncement, 1);
                    }else {
                        return Result.fail("没有公告数据");
                    }
                } else {
                    return Result.fail("该学号不存在");
                }
            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
    }
}
